# -*- coding: utf-8 -*-
"""
认证和权限验证工具
@api-version: 1.0.0
"""

import os
from functools import wraps
from flask import request, g
from backend.models.user import User
from backend.models.session import UserSession
from backend.utils.response import unauthorized_response, forbidden_response

# 测试环境永久有效的管理员token
TEST_ADMIN_TOKEN = os.environ.get('TEST_ADMIN_TOKEN', 'test-admin-token-for-development')

def token_required(f):
    """Token验证装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        token = None
        
        # 从请求头获取token
        auth_header = request.headers.get('Authorization')
        if auth_header and auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
        
        # 测试环境特殊处理：检查X-Test-Auth头
        test_auth = request.headers.get('X-Test-Auth') == 'true'
        
        if not token:
            return unauthorized_response('缺少Token')
        
        # 检查是否使用测试token
        if token == TEST_ADMIN_TOKEN:
            # 为测试token创建管理员用户
            admin_user = User.query.filter_by(is_admin=True).first()
            if not admin_user:
                # 如果没有管理员用户，使用ID=1的用户
                admin_user = User.query.get(1)
                if not admin_user:
                    return unauthorized_response('测试环境中未找到可用用户')
            
            # 将管理员用户信息存储到g对象中
            g.current_user = admin_user
            g.current_session = None  # 测试token没有关联会话
            return f(*args, **kwargs)
        
        try:
            # 验证token
            session = UserSession.query.filter_by(token=token).first()
            if not session:
                return unauthorized_response('Token无效')
            
            if session.is_expired():
                # 删除过期会话
                from backend.models import db
                db.session.delete(session)
                db.session.commit()
                return unauthorized_response('Token已过期')
            
            # 获取用户信息
            user = User.query.get(session.user_id)
            if not user or not user.is_active():
                return unauthorized_response('用户不存在或已被禁用')
            
            # 将用户信息存储到g对象中
            g.current_user = user
            g.current_session = session
            
        except Exception as e:
            response, status_code = unauthorized_response('Token验证失败')
            return response
        
        return f(*args, **kwargs)
    
    return decorated_function

def admin_required(f):
    """管理员权限验证装饰器"""
    @wraps(f)
    @token_required
    def decorated_function(*args, **kwargs):
        if not g.current_user.is_admin:
            return forbidden_response('需要管理员权限')
        return f(*args, **kwargs)
    
    return decorated_function

def get_client_ip():
    """获取客户端IP地址"""
    if request.headers.get('X-Forwarded-For'):
        return request.headers.get('X-Forwarded-For').split(',')[0].strip()
    elif request.headers.get('X-Real-IP'):
        return request.headers.get('X-Real-IP')
    else:
        return request.remote_addr

def get_user_agent():
    """获取用户代理信息"""
    return request.headers.get('User-Agent', '')

def get_current_user():
    """获取当前用户
    
    Returns:
        User: 当前用户对象，如果未登录返回None
    """
    if hasattr(g, 'current_user'):
        return g.current_user
    return None

# 为了兼容性，添加login_required别名
login_required = token_required